package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.item.entity.Sku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分析购物车数据的结构
 * redis中有五种数据结构： string， hash， list， set， zSet
 * 这里采用hash结构的数据：<userId, <skuId, Sku>>
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ItemClient itemClient;


    public void addCart(Cart cart) {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //提供当前用户在redis中的购物车数据的key
        String key = LyConstants.CART_PRE+userId;
        //通过当前用户在redis中的购物车的key获取到对应的购物车对象
        BoundHashOperations<String, String, String> hash = redisTemplate.boundHashOps(key);
        //获取新添加的购物车对象的hashKey
        String hashKey = cart.getSkuId().toString();
        //判断新添加的购物车对象是否存在于目前的购物车集合中
        Boolean hasKey = hash.hasKey(hashKey);
        //如果存在
        if(hasKey){
            //获取到购物车中对应的对象
            String redisCartStr = hash.get(hashKey);
            //把字符串格式的购物车对象转成对象
            Cart redisCart = JsonUtils.toBean(redisCartStr, Cart.class);
            //把新添加的购物车对象的数量与之前的购物车中此对象的数量进行合并
            cart.setNum(cart.getNum()+redisCart.getNum());
        }
        //添加购物车
        hash.put(hashKey, JsonUtils.toString(cart));
    }

    public List<Cart> findCarts() {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //提供当前用户在redis中的购物车数据的key
        String key = LyConstants.CART_PRE+userId;
        //判断当前用户是否有购物车
        if(!redisTemplate.hasKey(key)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //通过key获取hash
        BoundHashOperations<String, String, String> hash = redisTemplate.boundHashOps(key);
        //判断hash是否为空
        if(hash==null || hash.size()==0){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //获取购物车列表
        List<Cart> carts = hash.values().stream().map(cart -> JsonUtils.toBean(cart, Cart.class)).collect(Collectors.toList());
        return carts;
    }

    public void addCarts(List<Cart> carts) {
        carts.forEach(cart -> {
            addCart(cart);
        });
    }

    public void deleteCart(HashMap<Long, List<Long>> carts){
        try {
            carts.entrySet().forEach(entry->{
                String userId = String.valueOf(entry.getKey());
                List<Long> skuIds = entry.getValue();
                String key = LyConstants.CART_PRE + userId;
                HashOperations<String, String, String> hash = redisTemplate.opsForHash();
                skuIds.forEach(sku->{
                    String skuStr = sku.toString();
                    hash.delete(key, skuStr);
                });
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Boolean addGuanzhu(Cart cart) {
        Long userId = UserHolder.getUserId();
        //提供当前用户在redis中的收藏数据的key
        String key = LyConstants.GUANZHU_PRE+userId;
        BoundHashOperations<String, String, String> hash = redisTemplate.boundHashOps(key);
        //获取新添加的购物车对象的hashKey
        String hashKey = cart.getSkuId().toString();
        //判断新添加的购物车对象是否存在于目前的购物车集合中
        Boolean hasKey = hash.hasKey(hashKey);
        //如果存在
        if(hasKey){
            //返回已存在
            return true;
        }
        //添加收藏
        hash.put(hashKey,JsonUtils.toString(cart));

        return false;
    }

    public List<Cart> loadGuanZhu() {
        List<Cart> carts=null;
        Long userId = UserHolder.getUserId();
        //提供当前用户在redis中的收藏数据的key
        String key = LyConstants.GUANZHU_PRE+userId;
        BoundHashOperations<String, String, String> hash = redisTemplate.boundHashOps(key);
        if(hash.size()!=0)
            carts=hash.values().stream().map(cart -> JsonUtils.toBean(cart,Cart.class)).collect(Collectors.toList());
        return carts;
    }

    public void addCartByskuId(Cart cart) {
        List<Long> skuIds= new ArrayList<>();
        skuIds.add(cart.getSkuId());
        List<Sku> skus = itemClient.findSkusByIds(skuIds);
        Sku sku = skus.get(0);
        cart.setOwnSpec(sku.getOwnSpec());
        cart.setNum(1);
        addCart(cart);
    }

    public Map<String, Object> findPrice(Long id,Long price) {
        Map<String, Object> map=new HashMap<>();
        //查询价格
        List<Long> skuIds= new ArrayList<>();
        skuIds.add(id);
        List<Sku> skus = itemClient.findSkusByIds(skuIds);
        Sku sku = skus.get(0);
        if(sku==null)
            throw new LyException(404,"你的商品不存在");
        if(sku.getPrice()<price){
            map.put("result",true);
            map.put("price",sku.getPrice());
            return map;
        }
        map.put("result",false);
        return map;
    }
}
